package com.daiqile.myinterest.fragement;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.daiqile.myinterest.BaseFragment;
import com.daiqile.myinterest.MyMainActivity;
import com.daiqile.myinterest.R;
import com.daiqile.myinterest.activity.MapDetailActivity;
import com.daiqile.myinterest.activity.POINearByActivity;
import com.vondear.rxtools.RxPhotoTool;
import com.vondear.rxtools.RxSPTool;
import com.vondear.rxtools.view.dialog.RxDialogChooseImage;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import jp.wasabeef.glide.transformations.CropCircleTransformation;

import static android.app.Activity.RESULT_OK;
import static com.vondear.rxtools.view.dialog.RxDialogChooseImage.LayoutType.NO_TITLE;

/**
 * A simple {@link Fragment} subclass.
 */
public class ThreeFragment extends BaseFragment {
    @BindView(R.id.img_logo)
    ImageView imgLogo;
    private Activity mContext;
    private Uri resultUri;

    public ThreeFragment() {
        // Required empty public constructor
    }

    @Override
    protected int getContentView() {
        return R.layout.fragment_three;
    }

    @Override
    protected void initViews() {
        mContext = getActivity();
        Glide.with(mContext).
                load(R.mipmap.logo).
                into(imgLogo);
    }

    @OnClick(R.id.img_logo)
    public void onViewClicked() {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(mContext, NO_TITLE);
        dialogChooseImage.show();
    }

    //第三方开源图片裁剪框架Ucrop
    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);
        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));
        Uri destinationUri = Uri.fromFile(new File(getActivity().getCacheDir(), imageName + ".jpeg"));
        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置UCropActivity toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(getActivity(), R.color.material_blue_300));
        //设置UCropActivity状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(getActivity(), R.color.material_blue_300));
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        options.setImageToCropBoundsAnimDuration(666);
        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(getActivity());
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {
        Glide.with(mContext)
                .load(uri)
                .diskCacheStrategy(DiskCacheStrategy.RESULT)
                .bitmapTransform(new CropCircleTransformation(mContext))
                .thumbnail(0.5f)
                .placeholder(R.mipmap.logo)
                .priority(Priority.LOW)
                .error(R.mipmap.logo)
                .fallback(R.mipmap.logo)
                .into(imageView);
        return (new File(RxPhotoTool.getImageAbsolutePath(getActivity(), uri)));
    }

    //回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(data.getData());
                }
                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    initUCrop(RxPhotoTool.imageUriFromCamera);
                }
                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                Glide.with(mContext).
                        load(RxPhotoTool.cropImageUri).
                        diskCacheStrategy(DiskCacheStrategy.RESULT).
                        bitmapTransform(new CropCircleTransformation(mContext)).
                        thumbnail(0.5f).
                        placeholder(R.mipmap.logo).
                        priority(Priority.LOW).
                        error(R.mipmap.logo).
                        fallback(R.mipmap.logo).
                        into(imgLogo);
                break;
            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    roadImageView(resultUri, imgLogo);
                    RxSPTool.putContent(mContext, "AVATAR", resultUri.toString());
                    //获取默认的下载目录
                    String downloadsDirectoryPath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();

                    //uri.getLastPathSegment() 解析最后一个地址段
                    String filename = String.format("%d_%s", Calendar.getInstance().getTimeInMillis(), resultUri.getLastPathSegment());
                    File saveFile = new File(downloadsDirectoryPath, filename);
                    //保存下载的图片
                    FileInputStream inStream = null;
                    FileOutputStream outStream = null;
                    FileChannel inChannel = null;
                    FileChannel outChannel = null;
                    try {
                        inStream = new FileInputStream(new File(resultUri.getPath()));
                        outStream = new FileOutputStream(saveFile);
                        inChannel = inStream.getChannel();
                        outChannel = outStream.getChannel();
                        inChannel.transferTo(0, inChannel.size(), outChannel);
                        Toast.makeText(getActivity(), "裁切后的图片保存在：" + saveFile.getAbsolutePath(), Toast.LENGTH_SHORT).show();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            outChannel.close();
                            outStream.close();
                            inChannel.close();
                            inStream.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                Toast.makeText(getActivity(), "裁切失败", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    @OnClick({R.id.me_information, R.id.me_location, R.id.me_around, R.id.me_other})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.me_information:
                break;
            case R.id.me_location:
                startActivity(new Intent(getActivity(),MapDetailActivity.class));
                break;
            case R.id.me_around:
                startActivity(new Intent(getActivity(),POINearByActivity.class));
                break;
            case R.id.me_other:
                startActivity(new Intent(getActivity(),MyMainActivity.class));
                break;
        }
    }
}
